﻿/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 *
 *
 */

import React, {Component} from 'react';
import {
  StyleSheet,
  Image,
  Text,
  TextInput,
  TouchableOpacity,
  Dimensions,
  Alert,
  View,
  Modal,
} from 'react-native';

import Toast from './component/Toast';
import PublicComponent from './component/PublicComponent';
import {scaleHeight} from './component/ScreenUtil';
import StorageTools from './component/StorageTools';
import getStyles from '../style/styles';
import axiosInstance from './utils/request';
import NetInfo from '@react-native-community/netinfo';
import {reset} from './utils/navUtil';
import {BaseHost} from './utils/apiPath';

//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;

let styles = {};
class LoginView extends Component {
  static navigationOptions = {
    title: '用户登录',
    headerStyle: {
      backgroundColor: 'rgba(0, 191 ,255, 0.5)',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  };

  constructor(props) {
    super(props);
    this.userId = '';
    this.state = {
      userName: '',
      password: '1q2w3e4r',
      isConnected: null,
      animationType: 'none', //none slide fade
      transparent: true, //是否透明显
      modalVisible: false, //模态场景是否可见
    };
  }

  //页面的组件渲染完毕（render）之后执行
  componentDidMount() {
    //检测网络是否连接
    NetInfo.fetch().then(({isConnected}) => {
      console.log('当前网络状态： ' + (isConnected ? 'online' : 'offline'));
      if (!isConnected) {
        Alert.alert('提示', '网络连接异常，请检查网络配置！');
      }

      this.setState({isConnected});
    });
    StorageTools.get('username', '15184766025')
      .then(results => {
        // console.log(results);
        this.setState({
          userName: results,
        });
      })
      .catch(err => {});

    StorageTools.get('fontSize', '37')
      .then(results => {
        global.styles.fontSize = results;
      })
      .catch(err => {});

    StorageTools.get('user').then(result => {
      if (result) {
        global.user = result;
        this.onLoginSuccess();
      }
    });

    StorageTools.get('host', BaseHost)
      .then(results => {
        console.log('host:', results);
        this.setState({
          host: results,
        });
        global.server.url = results;
      })
      .catch(err => {});
  }

  checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
      return response;
    }
  }

  parseJSON(response) {
    return response.json();
  }

  login = () => {
    let URL = global.server.url + '/login';
    console.log('url---', URL);
    // 请求具有给定ID的用户
    axiosInstance
      .get(URL, {
        params: {
          username: this.state.userName,
          password: this.state.password,
        },
      })
      .then(response => {
        console.log('login---', response);
        const {longUser, accountCycle} = response;
        let msg = longUser.msg;
        if (typeof msg == 'undefined') {
          StorageTools.remove('username');
          //登录成功后将租户Id,用户名和密码写入缓存
          StorageTools.save('username', this.state.userName);
          StorageTools.save('password', this.state.password);

          global.user.loginState = true; //设置登录状态
          global.user.userData = {
            sessionId: longUser.sessionId,
            userType: longUser.userType,
            name: longUser.name,
          }; //保存用户数据
          global.user.accountCycle = {currMonth: accountCycle.month}; //保存账务周期
          StorageTools.save('user', global.user);
          this.onLoginSuccess();
        } else {
          Alert.alert('登录提示', msg);
        }
      })
      .catch(function (error) {
        console.log(error);
        Alert.alert('登录异常:手机号或密码错误！');
      });
  };

  //跳转到第二个页面去
  onLoginSuccess = () => {
    reset(this.props.navigation, 'IndexScreen', {userId: this.userId});
    // this.props.navigation.navigate('MenuScene', {userId:this.userId});//跳转到用户页面
  };

  clear = () => {
    this.setState({
      userName: '',
      password: '',
    });
  };

  setUserName(text) {
    this.setState(state => {
      return {
        userName: text,
      };
    });
  }

  setPassword(text) {
    this.setState(state => {
      return {
        password: text,
      };
    });
  }

  setModalVisible = visible => {
    this.setState({modalVisible: visible});
  };

  save() {
    let host = this.state.host;
    StorageTools.remove('username');
    StorageTools.save('host', host);
    global.server.url = host;
    this.setModalVisible(false);
    Toast.show('保存成功！');
  }

  render() {
    styles = getStyles();
    return (
      <View style={style.container}>
        {PublicComponent.initStatusBar(false)}
        {PublicComponent.initTitleBar('用户登录')}
        {/*头像*/}
        <Image style={style.circleImage} source={require('../img/logo.png')} />
        {/*账户*/}
        <TextInput
          style={styles.textInput}
          placeholder={'输入手机号'}
          keyboardType={'numeric'}
          maxLength={11}
          value={this.state.userName + ''}
          onChangeText={text => this.setUserName(text)}
          //输入框下划线
          underlineColorAndroid={'transparent'}
        />
        {/*密码*/}
        <TextInput
          style={styles.textInput}
          placeholder={'输入密码'}
          value={this.state.password + ''}
          secureTextEntry={true}
          onChangeText={text => this.setPassword(text)}
          underlineColorAndroid={'transparent'}
        />
        <View style={styles.settingStyle}>
          <TouchableOpacity onPress={this.login} style={style.loginTextView}>
            <Text style={style.loginText}>登录</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.clear()}
            style={style.loginTextView}>
            <Text style={style.loginText}>清空</Text>
          </TouchableOpacity>
        </View>
        <View>
          <TouchableOpacity
            onPress={() => {
              this.setModalVisible(true);
            }}>
            <Text
              style={{
                fontWeight: 'bold',
                marginTop: 70,
                width: 60,
                textAlign: 'center',
              }}>
              网络配置
            </Text>
          </TouchableOpacity>
        </View>
        <View style={{alignItems: 'center', flex: 1}}>
          <Modal
            animationType={this.state.animationType}
            transparent={this.state.transparent}
            visible={this.state.modalVisible}
            onRequestClose={() => {
              this.setModalVisible(false);
            }}>
            <View
              style={[
                styles.modalContainer,
                {backgroundColor: 'rgba(0, 0, 0, 0.5)'},
              ]}>
              <View
                style={[
                  styles.innerContainer,
                  {backgroundColor: '#F0F8FF', padding: 20},
                ]}>
                <View style={styles.row}>
                  <View>
                    <Text style={styles.tips}>请输入服务端地址:</Text>
                  </View>
                  <TextInput
                    style={{
                      height: 35,
                      width: width * 1.4,
                      backgroundColor: 'white',
                    }}
                    placeholder={'如http://IP地址或域名:端口号'}
                    value={this.state.host}
                    onChangeText={text => {
                      this.host = text;
                      this.setState({host: text});
                    }}
                    //输入框下划线
                    underlineColorAndroid={'transparent'}
                  />
                </View>
                <View style={styles.settingStyle}>
                  <Text
                    onPress={this.save.bind(this)}
                    style={{fontSize: 20, marginTop: 10}}>
                    保存
                  </Text>
                  <Text
                    onPress={this.setModalVisible.bind(this, false)}
                    style={{fontSize: 20, marginTop: 10}}>
                    关闭
                  </Text>
                </View>
              </View>
            </View>
          </Modal>
        </View>
      </View>
    );
  }
}

var width = WIN_WIDTH / 2;
const style = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#dddddd',
    //设置次轴的对齐方式
    alignItems: 'center',
  },
  circleImage: {
    borderColor: 'white',
    marginTop: 60,
    marginBottom: 25,
  },
  loginText: {
    color: '#ffffff',
    fontWeight: 'bold',
    width: 55,
    textAlign: 'center',
  },
  loginTextView: {
    marginTop: 10,
    height: 30,
    backgroundColor: '#3281DD',
    borderRadius: 5,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

//输出本类  记住一定是exports  不是  export
module.exports = LoginView;
